package com.tz.farmer.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpUtils {
    private static String charset = "utf-8";
//    private static HttpClient httpClient = HttpClients.createDefault();
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);


    public static String doGet(String urlPath, HashMap<String, Object> params)
            throws Exception {
        StringBuilder sb = new StringBuilder(urlPath);
        if (params != null && !params.isEmpty()) { // 说明有参数
            sb.append("?");

            Set<Map.Entry<String, Object>> set = params.entrySet();
            for (Map.Entry<String, Object> entry : set) { // 遍历map里面的参数
                String key = entry.getKey();
                String value = "";
                if (null != entry.getValue()) {
                    value = entry.getValue().toString();
                    // 转码
                    value = URLEncoder.encode(value, "UTF-8");
                }
                sb.append(key).append("=").append(value).append("&");
            }

            sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
        }
        // System.out.println(sb.toString());
        URL url = new URL(sb.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000); // 5s超时
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == 200) {// HttpStatus.SC_OK ==
            // 200
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(),"UTF-8"));
            StringBuilder sbs = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sbs.append(line);
            }
            // JSONObject jsonObject = new JSONObject(sbs.toString());
            return sbs.toString();
        }

        return null;
    }


    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String doPost(String url, Map<String, Object> params) throws Exception {
        //创建post请求对象
        HttpPost httppost = new HttpPost(url);
        // 获取到httpclient客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //添加参数
            httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8")));
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String resultString = EntityUtils.toString(resEntity, charset);
                    return resultString;
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            httpclient.close();
        }
        return null;
    }



    public static String getZnyp(String page){

//            Map map = new HashMap<>();
//            map.put("token", "YNXBKwffSseszcIvKVeGXsgF4+yrvkzD");
//            map.put("page", page);
//            return HttpUtils.doPost("https://fylz.zjagri.cn/zc/thirdPart/api/hgz/getAll.mhtml", map);
        try {
            String postURL="https://fylz.zjagri.cn/zc/thirdPart/api/hgz/getAll.mhtml";
            PostMethod postMethod = null;
            postMethod = new PostMethod(postURL) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            NameValuePair[] data = {
                    new NameValuePair("token","YNXBKwffSseszcIvKVeGXsgF4+yrvkzD"),
                    new NameValuePair("page",page)
            };
            postMethod.setRequestBody(data);
            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            String result = postMethod.getResponseBodyAsString() ;
            return result;
        } catch (Exception e) {
            logger.info("请求异常"+e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }

    }


}
